package com.xuxingcan.findmyvoice.Activity;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.rey.material.widget.ProgressView;
import com.xuxingcan.findmyvoice.Model.SendMessageModel;
import com.xuxingcan.findmyvoice.R;
import com.xuxingcan.findmyvoice.Util.AudioUtil;
import com.xuxingcan.findmyvoice.Util.BitmapUtil;
import com.xuxingcan.findmyvoice.Util.LeanCloudUtil;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by xuxingcan on 16-3-29.
 */
public class NewItemActivity extends BaseActivity {
    private static final String TAG = "NewItemActivity";
    private ImageView voiceDegree, voiceBtn, playBtn;
    private GridView mGridView;
    private TextView recordTime, sendBtn;
    private View voiceLayout;
    private Handler mHandler;
    private AnimationDrawable animationDrawable;
    private MediaRecorder mRecorder;
    private File tempFile;
    private ArrayList<Bitmap> bitmaps = new ArrayList<>();
    private PicAdapter mPicAdapter;
    private Bitmap plusBitmap;
    private EditText contentEditText, headEditText;
    private AlertDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_item);
        tempFile = new File(getDir("record", MODE_PRIVATE), "temp.mp4");
        tempFile.delete();
        plusBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.plus);
        initView();
        setClick();
    }

    private void initView() {
        voiceDegree = (ImageView) findViewById(R.id.voice_degree);
        voiceLayout = findViewById(R.id.voice_layout);
        voiceBtn = (ImageView) findViewById(R.id.voice_btn);
        playBtn = (ImageView) findViewById(R.id.play_btn);
        recordTime = (TextView) findViewById(R.id.record_time);
        mGridView = (GridView) findViewById(R.id.pic_gridview);
        mPicAdapter = new PicAdapter(this, bitmaps);
        mGridView.setAdapter(mPicAdapter);
        sendBtn = (TextView) findViewById(R.id.send);
        contentEditText = (EditText) findViewById(R.id.content_edit);
        headEditText = (EditText) findViewById(R.id.head_edit);
    }

    private void setClick() {
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        voiceBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.d(TAG, "ACTION_DOWN");
                        if (mRecorder == null) {
                            startRecording();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.d(TAG, "ACTION_UP");
                        stopRecording();
                        break;
                }
                return true;
            }
        });
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tempFile.exists()) {
                    try {
                        MediaPlayer mPlayer = new MediaPlayer();
                        mPlayer.setDataSource(tempFile.getAbsolutePath());
                        mPlayer.prepare();
                        AudioUtil.muteAudioFocus(NewItemActivity.this, true);
                        mPlayer.start();
                        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                AudioUtil.muteAudioFocus(NewItemActivity.this, false);
                            }
                        });
                    } catch (Exception e) {
                        Log.e(TAG, "播放失败");
                    }
                }
            }
        });
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!tempFile.exists()) {
                    showDialog("发生了一点错误", "请录一段语音", "我知道了");
                    return;
                }
                if (recordTime.getTag() == null) {
                    showDialog("发生了一点错误", "请录一段语音", "我知道了");
                    return;
                }
                if (bitmaps == null || bitmaps.size() == 0) {
                    showDialog("发生了一点错误", "请添加至少一张图片", "我知道了");
                    return;
                }
                if (contentEditText.getText().toString() == null || contentEditText.getText().toString().length() == 0) {
                    showDialog("发生了一点错误", "请输入内容", "我知道了");
                    return;
                }
                if (headEditText.getText().toString() == null || headEditText.getText().toString().length() == 0) {
                    showDialog("发生了一点错误", "请输入标题", "我知道了");
                    return;
                }
                showLoadingProgress();
                SendMessageModel msg = new SendMessageModel();
                msg.setAudioFile(tempFile.getAbsolutePath());
                msg.setAudioTime((Integer) recordTime.getTag());
                msg.setBitmaps(bitmaps);
                msg.setContent(contentEditText.getText().toString());
                msg.setHead(headEditText.getText().toString());
                LeanCloudUtil.sendMsg(NewItemActivity.this, msg, new LeanCloudUtil.sendMsgCallBack() {
                    @Override
                    public void onError(Exception e) {
                        stopLoadingProgress();
                        showShortToast(e.getMessage());
                    }

                    @Override
                    public void onSuccess() {
                        stopLoadingProgress();
                        showShortToast("onSuccess");
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            ContentResolver cr = this.getContentResolver();
            try {
                Bitmap bitmap = BitmapUtil.getBitmapWithLowMemory(BitmapFactory.decodeStream(cr.openInputStream(uri)), 500, 500);
                bitmaps.add(bitmap);
                mPicAdapter.setBitmapList(bitmaps);
                mPicAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                Log.e("Exception", e.getMessage(), e);
            } catch (OutOfMemoryError ee) {

            }
        }
    }

    private void startRecording() {
        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mRecorder.setOutputFile(tempFile.getAbsolutePath());
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        try {
            mRecorder.prepare();
            mRecorder.start();
            AudioUtil.muteAudioFocus(this, true);
            voiceLayout.setVisibility(View.VISIBLE);
            voiceDegree.setImageResource(R.drawable.degree_animation);
            animationDrawable = (AnimationDrawable) voiceDegree.getDrawable();
            animationDrawable.setOneShot(false);
            animationDrawable.start();
        } catch (Exception e) {
            Log.e(TAG, "prepare() failed");
            showShortToast(e.getMessage());
        }
    }

    private void stopRecording() {
        if (animationDrawable != null) {
            animationDrawable.stop();
        }
        if (mRecorder != null) {
            mRecorder.stop();
            mRecorder = null;
        }
        voiceLayout.setVisibility(View.GONE);
        AudioUtil.muteAudioFocus(this, false);
        if (tempFile.exists()) {
            MediaPlayer mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(tempFile.getAbsolutePath());
                mPlayer.prepare();
                setTime(mPlayer.getDuration());
                mPlayer.release();
            } catch (Exception e) {
                Log.e(TAG, "播放失败");
            }
        }
    }

    private void setTime(int time) {
        recordTime.setText(time / 1000 + "'" + time % 1000 / 10);
        recordTime.setTag(time);
    }

    private class ViewHolder {
        ImageView mImageView;
    }

    private class PicAdapter extends BaseAdapter {
        private Context mContext;
        private ArrayList<Bitmap> bitmaps = new ArrayList<>();

        public PicAdapter(Context mContext, ArrayList<Bitmap> bitmaps) {
            this.mContext = mContext;
            this.bitmaps = (ArrayList<Bitmap>) bitmaps.clone();
            this.bitmaps.add(plusBitmap);
        }

        public void setBitmapList(ArrayList<Bitmap> bitmaps) {
            this.bitmaps = (ArrayList<Bitmap>) bitmaps.clone();
            this.bitmaps.add(plusBitmap);
        }

        @Override
        public int getCount() {
            if (bitmaps.size() > 4) {
                return 4;
            } else {
                return bitmaps.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return bitmaps.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater mInflater = LayoutInflater.from(mContext);
            ViewHolder mViewHolder = null;
            if (convertView == null) {
                mViewHolder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.pic_item, null);
                mViewHolder.mImageView = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(mViewHolder);
            } else {
                mViewHolder = (ViewHolder) convertView.getTag();
            }
            mViewHolder.mImageView.setImageBitmap(bitmaps.get(position));
            if (position == getCount() - 1) {
                mViewHolder.mImageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intent, 0);
                    }
                });
            } else {
                mViewHolder.mImageView.setOnClickListener(null);
            }
            if (position == 3) {
                mViewHolder.mImageView.setVisibility(View.GONE);
            }
            return convertView;
        }
    }

    private void showLoadingProgress() {
        progressDialog = new AlertDialog.Builder(this).create();
        progressDialog.show();
        progressDialog.setCancelable(false);
        progressDialog.getWindow().setContentView(R.layout.progress_dialog);
        progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        ((ProgressView) progressDialog.findViewById(R.id.progress)).start();
    }

    private void stopLoadingProgress() {
        if (progressDialog != null) {
            ProgressView mProgressView = (ProgressView) progressDialog.findViewById(R.id.progress);
            mProgressView.stop();
            mProgressView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    progressDialog.dismiss();
                    finish();
                }
            }, 200);
        }
    }
}
